** Creating additional variables: large democratic swings

use "$project_path/data/3_cleaned/outcomes", clear
egen country_id = group(Country)
xtset country_id Year
gen change_democ = F.democracy_index - democracy_index
sum change_democ
local cutoff = r(sd)

// Positive democracy swing
gen pos_swing_democ_12 = ((F2.democracy_index - F.democracy_index) > `cutoff')
gen pos_swing_democ_23 = ((F3.democracy_index - F2.democracy_index) > `cutoff')
gen pos_swing_democ_34 = ((F4.democracy_index - F3.democracy_index) > `cutoff')
replace pos_swing_democ_12 = . if F2.democracy_index==. | F.democracy_index==.
replace pos_swing_democ_23 = . if F3.democracy_index==. | F2.democracy_index==.
replace pos_swing_democ_34 = . if F4.democracy_index==. | F3.democracy_index==.
egen pos_swing_democ = rowmax(pos_swing_democ_12 pos_swing_democ_23 pos_swing_democ_34)

// Negative democracy swing
gen neg_swing_democ_12 = (-(F2.democracy_index - F.democracy_index) > `cutoff')
gen neg_swing_democ_23 = (-(F3.democracy_index - F2.democracy_index) > `cutoff')
gen neg_swing_democ_34 = (-(F4.democracy_index - F3.democracy_index) > `cutoff')
replace neg_swing_democ_12 = . if F2.democracy_index==. | F.democracy_index==.
replace neg_swing_democ_23 = . if F3.democracy_index==. | F2.democracy_index==.
replace neg_swing_democ_34 = . if F4.democracy_index==. | F3.democracy_index==.
egen neg_swing_democ = rowmax(neg_swing_democ_12 neg_swing_democ_23 neg_swing_democ_34)

keep Country Year pos_swing_democ neg_swing_democ
lab var pos_swing_democ "Large positive democratic swing"
lab var neg_swing_democ "Large negative democratic swing"

notes pos_swing_democ : Source - V-Dem
notes neg_swing_democ : Source - V-Dem

tempfile large_swing_democ
save `large_swing_democ'

use "$project_path/data/4_regdata/regdata.dta", clear
merge m:1 Country Year using `large_swing_democ', keep(master match) nogen

** Regressions

log using "$project_path/output/appendix_tables/Appendix_Table_D4.smcl", replace

local variables = "democracy_index polyarchy egal liberal partip delib women_emp civ_lib pol_rights polity_score polcomp xconst voice_account dem_anrr democracy_bmr democracy_cgv pos_swing_democ neg_swing_democ"

foreach v in democracy_index polyarchy egal liberal partip delib women_emp civ_lib pol_rights polity_score polcomp xconst voice_account dem_anrr democracy_bmr democracy_cgv {
	rdrobust std_diff_m1_`v' runvar, all
}
rdrobust pos_swing_democ runvar, all
rdrobust neg_swing_democ runvar, all

log close

** Building .tex table

//Generate a temporary dta file with variables description. We use an id variable that follows the order of the local `variables'.
preserve
gen description = ""

local i = 1
foreach v in `variables'{
	
	if "`v'" == "democracy_index" local description = "Democracy index"
	if "`v'" == "polyarchy" local description = "Electoral democracy index"
	if "`v'" == "egal" local description = "Egalitarian component index"
	if "`v'" == "liberal" local description = "Liberal component index"
	if "`v'" == "partip" local description = "Participatory component index"
	if "`v'" == "delib" local description = "Deliberative component index"
	if "`v'" == "women_emp" local description = "Women political empowerment"
	if "`v'" == "civ_lib" local description = "Civil liberties index"
	if "`v'" == "pol_rights" local description = "Political rights index"
	if "`v'" == "polity_score" local description = "Polity IV score"
	if "`v'" == "polcomp" local description = "Political competitiveness"
	if "`v'" == "xconst" local description = "Executive constraints"
	if "`v'" == "voice_account" local description = "Voice and accountability"
	if "`v'" == "dem_anrr" local description = "Dichotomous democracy measure"
	if "`v'" == "democracy_bmr" local description = "Dichotomous democracy measure"
	if "`v'" == "democracy_cgv" local description = "Dichotomous democracy measure"
	if "`v'" == "pos_swing_democ" local description = "Large positive democratic swing"
	if "`v'" == "neg_swing_democ" local description = "Large negative democratic swing"
	
	qui replace description = "`description'" in `i'
	
	local ++i
}
keep description 
drop if description == ""
gen id = _n
tempfile description_dta
save `description_dta'
restore

//Generate a temporary dta file with source variable
preserve
gen source = ""
local i = 1
foreach v in `variables' {
	
	replace source = "``v'[note1]'" in `i'
	local ++i
	
}	
keep source
drop if source == ""
gen id = _n
replace source = substr(source, 9,.)
tempfile source_dta
save `source_dta'
restore

//Prepare matrix of coefficients and other statistics from the regression
local rows : word count `variables'
local nrows `rows'
local ncols 4
mat Coefs = J(`nrows', `ncols', .)


local i = 1
foreach v in `variables' {
	if strpos("`v'", "_swing_democ") {
		rdrobust `v' runvar, all
		
		//Store estimates and stats
		local b_`i': di %5.3f e(tau_cl)
		local se_`i': di %5.3f e(se_tau_rb)
		local p_`i': di %5.3f e(pv_rb)
		loca N_`i': di %6.0f e(N)
		
		//Fill the matrix
		mat Coefs[`i',1] = `b_`i''
		mat Coefs[`i',2] = `se_`i''
		mat Coefs[`i',3] = `p_`i''	
		mat Coefs[`i',4] = `N_`i''
		
		local ++i
	}
	else {
		rdrobust std_diff_m1_`v' runvar, all
		
		//Store estimates and stats
		local b_`i': di %5.3f e(tau_cl)
		local se_`i': di %5.3f e(se_tau_rb)
		local p_`i': di %5.3f e(pv_rb)
		loca N_`i': di %6.0f e(N)
		
		//Fill the matrix
		mat Coefs[`i',1] = `b_`i''
		mat Coefs[`i',2] = `se_`i''
		mat Coefs[`i',3] = `p_`i''	
		mat Coefs[`i',4] = `N_`i''
		
		local ++i
	}
}

mat list Coefs

********************************************************************************
* 								EXPORT TABLE
********************************************************************************			
// Clear the dataset, and use the matrix as dataset			

clear
svmat Coefs

rename Coefs1 estimates
rename Coefs2 std_err
rename Coefs3 pval
rename Coefs4 N

gen outcome = ""

gen id = _n
order id outcome, first

tostring estimates, replace force format(%04.3f)

//Add stars
local 3_star 0.01
local 2_star 0.05
local 1_star 0.10

replace estimates = estimates + "***" if pval < `3_star'
replace estimates = estimates + "**" if  pval < `2_star' & pval > `3_star'
replace estimates = estimates + "*" if   pval < `1_star' & pval > `2_star'

foreach var in std_err pval{
	
	tostring `var', replace force format(%04.3f)
	
}

replace std_err = "(" + std_err + ")"
replace pval = "[" + pval + "]"

//Attach source variable and description
merge 1:1 id using `source_dta', assert(match) nogen
merge 1:1 id using `description_dta', assert(match) nogen

replace outcome = description

drop id description


label var outcome ""
label var estimates "Est."
label var std_err "SE"
label var pval "p-val"
label var N "N"
label var source "Source"
//Prepare texfile

local title "Effects on additional democracy variables"
local label_key "tab:democracy_variables_baseline"
local output "$project_path/output/appendix_tables/Appendix_Table_D4.tex"
local footnote = "\emph{Notes}: This table reports RD estimates corresponding to equation (\ref{eq:baseline_rdd}) for measures of the quality of democracy, expressed in standard deviation terms. All dependent variables are computed as described in Section \ref{sec:outcomes}, apart from the 'Large positive democratic change' and 'Large negative democratic change' variables. For these outcomes, the dependent variable is a dummy variable equal to one if the country witnessed a year-to-year increase (resp., decrease) in the quality of democracy (as measured by V-Dem) that is larger than one standard deviation of the year-to-year changes of this variable between the year after the election and four years after the election."

texsave using "`output'", replace varlabels frag nofix 	location(H) ///
					      align(p{6.8cm} p{1.7cm} p{1.5cm} p{1.5cm} p{1.3cm} p{3.2cm}) ///
						  title("`title'")  ///
						  footnote("`footnote'") ///
						  marker("`label_key'") 
